<?php
/**
 * Created by PhpStorm.
 * User: shkj
 * Date: 2020/4/21
 * Time: 21:39
 */

namespace app\api\model;


use think\Db;
use think\Model;
use think\facade\Request;
class Goods extends Model
{
    public function attr(){
        return $this->hasMany('GoodsAttr','goods_id','id');
    }
    public function type(){

        return $this->belongsTo('Type','type_id','id');
    }


    // public function select(){
    //   $res = self::all([],'attr.name')->toArray();

    //    foreach ($res as $k=>$v){

    //        $v['goods_thumb']=explode(",",$v['goods_thumb']);
    //        $img =  $v['goods_thumb'];

    //            foreach ($img as $key => $value) {
    //                $img[$key]= Image::where('id', $value)->find();
    //        }

    //        $v['goods_thumb']=$img;


    //        foreach ($v['type'] as $key => $value){

    //            $v[$key]=$value;

    //            $res[$k] = $v;
    //        }
    //        unset($res[$k]['type']);

    //        foreach ($v['attr'] as $ik=>$iv){

    //            if(is_array($iv['name'])){

    //            foreach ($iv['name'] as $an=>$av){

    //                $iv[$an]=$av;
    //               $v[$ik]=$iv;
    //               $res[$k]['attr'][$ik] = $iv;

    //            }
    //             unset($res[$k]['attr'][$ik]['name']);

    //            }
      
    //        }
               

    //    }

    //   return_json(200,'查询成功',$res);
    // }

    public function select($pagenum=1,$pagesize=1){
    $map =[];
    $keywords = Request::param('query');
    if(!empty($keywords)){
    //条件2
     $map[] = ['goods_title','like','%'.$keywords.'%'];
}
    
    $res = db('goods')->field('id,goods_title,goods_price,on_sale,propaganda,create_time')->where($map)->page($pagesize,$pagenum)->select();
    $count = self::count();

    $info = array(
      'data'=>$res,
      'total'=>$count
      );
    return_json(200,'成功',$info);

    }

    public function search($data){
       $res = db('goods')->field('id,goods_title')->where('goods_title', 'like', '%'.$data.'%')->select();
 
        return_json(200,'查询成功',$res);
    }


    public function sel($store_id){
//        dump($store_id);
        $res = self::where('store_id',$store_id)->where('on_sale',1)->all([],'type,attr.name')->toArray();

        foreach ($res as $k=>$v){

            $v['goods_thumb']=explode(",",$v['goods_thumb']);
            $img =  $v['goods_thumb'];

            foreach ($img as $key => $value) {
                $img[$key]= Image::where('id', $value)->find();
            }

            $v['goods_thumb']=$img;
            foreach ($v['type'] as $key => $value){

                $v[$key]=$value;

                $res[$k] = $v;
            }
            unset($res[$k]['type']);

            foreach ($v['attr'] as $ik=>$iv){

               if(is_array($iv['name'])){

               foreach ($iv['name'] as $an=>$av){

                   $iv[$an]=$av;
                  $v[$ik]=$iv;
                  $res[$k]['attr'][$ik] = $iv;

               }
                unset($res[$k]['attr'][$ik]['name']);

               }
      
           }
        }

        return_json(200,'查询成功',$res);
    }

    public function cateSel($category_id){
      $res = self::where('category_id',$category_id)->
        where('on_sale',1)->paginate(5);

        return_json(200,'查询成功',$res);
    }

    public function typeSel($type_id){
        $res = self::where('type_id',$type_id)->
        where('on_sale',1)->paginate(5);


        return_json(200,'查询成功',$res);
    }

    public function show(){
        $res = self::where('propaganda',1)->where('on_sale',1)->with('type,attr.name')->select()->toArray();
        foreach ($res as $key=>$value){
            foreach ($value['type'] as $k=>$v){
                $value[$k]=$v;
                $res[$key]=$value;
            }

            unset($res[$key]['type']);

             foreach ($value['attr'] as $ik=>$iv){

               if(is_array($iv['name'])){

               foreach ($iv['name'] as $an=>$av){

                   $iv[$an]=$av;
                  $value[$ik]=$iv;
                  $res[$key]['attr'][$ik] = $iv;

               }
                unset($res[$key]['attr'][$ik]['name']);

               }
      
           }
        }
        return_json(200,'查询成功',$res);
    }


    public function detail($id){
        $res = self::where('id',$id)->with('attr.name')->find()->toArray();
        foreach ($res['attr'] as $key => $value) {
              
                 if($value['attr_type'] == 1){
                      $res['attrs'][$key] = $value;

                 }else{
                   $res['only'][$key] = $value;

                 }

                } 
                $res['attr'] = $res['attrs']; 
                unset($res['attrs']);
 
        $res['goods_thumb']=explode(",",$res['goods_thumb']);
        $img =  $res['goods_thumb'];
        foreach ($img as $key => $value) {
            $img[$key]= Image::where('id', $value)->find();
            unset($img[$key]['id']);
        }


        foreach ($res['attr'] as $key => $value) {
            if(is_array($value['name'])){
                foreach ($value['name'] as $k => $v) {
                    $value[$k]=$v;
                    $res['attr'][$key]=$value;
                }
                unset($res['attr'][$key]['name']);
            }
        }
        $res['goods_thumb']=$img;

        $newArr = [];
        foreach ($res['attr'] as $item){
            $newArr[$item['attr_name']][] = $item;
        }

        foreach ($newArr as $key=>$value) {

            $newArr[$key]['attr_name'] = $key;

            foreach ($value as $k => $v) {
                unset($newArr[$key][$k]);
                unset($value[$k]['attr_name']);
                $newArr[$key]['child'] = $value;


            }
        }
        $newArr =  array_values($newArr);
        $res['attr']=$newArr;

       
         $Info = model('evaluation')->img($id);
         $res['comment'] = $Info;
      
        return $res;
      
    }



     public function adminDetail($id){
        $res = self::where('id',$id)->find()->toArray();
       
 
        $res['goods_thumb']=explode(",",$res['goods_thumb']);
        $img =  $res['goods_thumb'];
        foreach ($img as $key => $value) {
            $img[$key]= Image::where('id', $value)->find();
            $img[$key]['url'] = $img[$key]['images']; 
            unset($img[$key]['images']);
            unset($img[$key]['id']);
        }


    
        $res['goods_thumb']=$img;
        
        $res['many'] = db('goods_attr')->where('goods_id',$res['id'])->where('attr_type',1)->hidden(['attr_type','goods_id'])->select();
        $res['only'] =  db('goods_attr')->where('goods_id',$res['id'])->where('attr_type',2)->hidden(['attr_type','goods_id','attr_stock','attr_price'])->select();
       foreach ($res['only'] as $k => $v) {
        $attr = db('attr')->field('attr_name')->where('id',$v['attr_id'])->find();
        $res['only'][$k]['attr_name'] = $attr['attr_name'];
       }
        $cate = db('category')->field('pid')->where('id',$res['type_id'])->find();
        $res['goods_cat'] = [$res['category_id'],$cate['pid'],$res['type_id']];
        foreach ($res['goods_cat'] as $key => $value) {
          $cates = db('category')->field('name')->where('id',$value)->find();
          $name[] = $cates['name']; 
        }
        $res['category_name'] = join("/", $name);
//dump($res);

        return_json(200,'查询成功',$res);
    }







    public function del($id){
        $res = self::where('id',$id)->find();
        $res['goods_thumb']=explode(",",$res['goods_thumb']);
        $del=db('goods')->delete($id);
        // 删除商品下面的商品属性
        db('goods_attr')->where(array('goods_id'=>$id))->delete();
        //删除商品下面的图片
        Image::destroy($res['goods_thumb']);
        if($del){
            return_json(200,'删除商品成功',true);
        }else{
            return_json(400,'删除商品失败！',false);
        }
    }


    public function add($data){
       $many = $data['goods_attrs'];//商品参数，选择
       $only = $data['attrs'];//商品属性，静态

       $data['create_time'] = time();
       // unset($data['goods_attr']);
      // goods_cat //分类id
      //图片添加
       foreach ($data['goods_thumb'] as $k=>$v) {
       $id = db('image')->insertGetId(['images'=>$v]);
       $ids[] = $id;
       }

      $data['goods_thumb']=implode(',', $ids);
       $info = array(
        'goods_title'=>$data['goods_title'],
        'goods_price'=>$data['goods_price'],
        'propaganda'=>$data['propaganda'],
        'goods_transport'=>$data['goods_transport'],
        'goods_freight'=>$data['goods_freight'],
        'goods_des'=>$data['goods_des'],
        'goods_thumb'=>$data['goods_thumb'],
        'category_id'=>$data['goods_cat'][0],
        'type_id'=>$data['goods_cat'][2],
        'create_time'=>$data['create_time'],
        'title_thumb'=>$data['title_thumb']
        );

      $goods_id = db('goods')->insertGetId($info);
  

//属性添加
        foreach ($many as $k => $v){
            $many[$k]['goods_id']=$goods_id ;
            $many[$k]['attr_type'] = 1;
        }

//静态参数添加
         foreach ($only as $k => $v){
            $only[$k]['goods_id']=$goods_id ;
            $only[$k]['attr_type'] = 2;
            unset($only[$k]['attr_name']);
        }


        $many = model('goodsAttr')->saveAll($many);
        $only = db('goods_attr')->insertAll($only);
       if($many && $only){
           return_json(200,'商品发布成功',true);
       }else{
           return_json(400,'商品发布失败',false);
       }

    }
    function getDiffArrayByFilter($value, $res)//二维数组取错误值
    {
        return array_filter(
            $value, function ($v) use ($res) {
            return !in_array($v, $res);
        }
        );
    }

    public function modify($gid,$data){
   
        $only = $data['only'];//商品属性
        $data['create_time'] = time();
       
        $many = $data['goods_attrs'];
   //表中有的
   $aid = db('goods_attr')->field('id')->where('attr_type',1)->where('goods_id',$gid)->select();
   foreach ($aid as $key => $value) {
      $aids[] = $value['id'];
   }
   //传输来的
   foreach ($many as $key => $value) {
     if(isset($value['id'])){
      db('goods_attr')->where('id',$value['id'])->update($value);
      $cid[] = $value['id'];  
     }else{
      $value['goods_id'] = $gid;
      db('goods_attr')->insert($value);
     }
   }
   //删除不一样的
   if(isset($cid) && isset($aids)){

      $did = array_diff($aids,$cid);
   }

 foreach ($did as $k => $v) {

    db('goods_attr')->where('id',$v)->delete();
 }


        //图片处理，1.查，2.增，3.比，4.取 5.删 6.组
        foreach ($data['goods_thumb'] as $key=>$value) {
            $res = Image::where('images', $value['url'])->find();
            if ($res) {
                $ids[] = $res['id'];
            }else{
                $id = db('image')->insertGetId(['images'=>$value['url']]);
                $ids[] = $id;//图片的id
            }
        }
     

        $good = self::where('id',$gid)->find();
        $id = explode(",",$good['goods_thumb']);
        $id = array_diff($id,$ids);//取出俩个数组的不同值
   
        foreach ($id as $k=>$v){
            db('image')->where('id',$v)->delete();
        }

        $data['goods_thumb']=implode(',', $ids);

        //商品静态属性处理
        foreach ($only as $k=>$v){
          unset($only[$k]['attr_name']);
            $res = db('goods_attr')->where('id',$only[$k]['id'])->update($only[$k]);
        }
        $info = array(
            'goods_title'=>$data['goods_title'],
            'title_thumb'=>$data['title_thumb'],
            'goods_thumb'=>$data['goods_thumb'],
            'goods_price'=>$data['goods_price'],
            'on_sale'=>$data['on_sale'],
            'goods_des'=>$data['goods_des'],
            'goods_transport'=>$data['goods_transport'],
            'goods_freight'=>$data['goods_freight'],
            'goods_sales'=>$data['goods_sales'],
            'goods_comments'=>$data['goods_comments'],
            'propaganda'=>$data['propaganda'],
            'create_time'=>time()


          );
     
        $goods = Goods::where('id',$gid)->update($info);

        if($res || $goods){

            return_json(200,'商品修改成功');
        }else{
            return_json(400,'商品修改失败');
        }

    }

    public function propaganda(){
      $res = self::where('propaganda',1)->where('on_sale',1)->order('goods_sales', 'desc')->select();
      if($res){
        return_json(200,'成功',$res);
      }else{
        return_json(400,'失败');
      }
    }
       public function status($id,$on_sale){
      $res = self::where('id',$id)->update(['on_sale'=>$on_sale]);
      if($res){
         return_json(200,'成功',true);
      }else{
        return_json(400,'失败',false);
      }
    }
       public function pstatus($id,$propaganda){
      $res = self::where('id',$id)->update(['propaganda'=>$propaganda]);
      if($res){
         return_json(200,'成功',true);
      }else{
        return_json(400,'失败',false);
      }
    }


}